package com.cf.controller;

import com.cf.entity.Result;
import com.cf.util.UUIDUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@CrossOrigin
public class ShowAndUploadController {

    @RequestMapping("/uploadFile")
    public Object uploadFile(MultipartFile file, HttpServletRequest request) throws IOException {
        String fname = file.getOriginalFilename();
        if(fname.contains("/")){
            fname = fname.substring(fname.lastIndexOf("/")+1);
        }
        fname = UUIDUtil.getUUID() + fname;
        String img = request.getRealPath("img");
        file.transferTo(new File(img, fname));
        return new Result(200,fname,null);
    }


    @RequestMapping("/showImg")
    public void showImg(String filename, HttpServletRequest request, HttpServletResponse response){
        try {
            String img = request.getRealPath("img");
            File file = new File(img, filename);
            FileInputStream fis = new FileInputStream(file);

            response.setHeader("Content-Disposition", "filename=" + filename);
            ServletOutputStream os = response.getOutputStream();
            IOUtils.copy(fis, os);
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
